/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package ticketbooking;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import javax.crypto.Cipher;
import javax.crypto.SealedObject;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import sun.misc.BASE64Encoder;


/**
 *
 * @author Kse7en
 */
public class RSA {
        
        public static byte[] encrypt(String plainText, Key publicKey) throws Exception {
                
                Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
                cipher.init(Cipher.ENCRYPT_MODE, publicKey);
                
                byte[] cipherText = cipher.doFinal(plainText.getBytes("UTF-8"));
            
                return cipherText;
        }
        
        public static String decrypt(byte[] cipherText, Key privateKey) throws Exception {
                
                Cipher cipherDecrypt = Cipher.getInstance("RSA/ECB/PKCS1Padding");
                cipherDecrypt.init(Cipher.DECRYPT_MODE, privateKey);
                
                String plainText = new String(cipherDecrypt.doFinal(cipherText), "UTF-8");
             
                return plainText; 
        }
        
        public static SealedObject encryptObj(Object plainObj, Key publicKey) throws Exception {
                
                assert(plainObj instanceof Serializable);
                
                Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
                cipher.init(Cipher.ENCRYPT_MODE, publicKey);
                
                SealedObject SO = new SealedObject((Serializable)plainObj, cipher);
                return SO;
        }
        
        public static Object decryptObj(SealedObject cipherObj, Key privateKey) throws Exception {
                
                Cipher cipherDecrypt = Cipher.getInstance("RSA/ECB/PKCS1Padding");
                cipherDecrypt.init(Cipher.DECRYPT_MODE, privateKey);
                
                Object plainObj = (Object) cipherObj.getObject(cipherDecrypt);
                return plainObj;
        }
        
}
